import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'


Vue.use(VueRouter)

const routes = [
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  // 创建路由规则
  {
    path:'/login',
    name:'login',
    component:()=>import('../views/Login.vue')
  },
  {
    path:'/',
    name:'layout',
    component:()=>import('../views/Layout.vue'),
    meta:{
      title:'首页'
    },
    // 嵌套路由
    children:[
      {
        path:'/goto2',
        name:'goto2',
        component:()=>import('../views/goto2.vue')
      },
      {
        path:'/users',
        name:'users',
        meta:{
          title:'用户管理'
        },
        component:()=>import('../views/Users.vue')
      },
      {
        path:'/rights',
        name:'rights',
        meta:{
          title:'权限列表'
        },
        component:()=>import('../views/Rights.vue')
      },
    ]
  },
]
const router = new VueRouter({
  routes
})
// 后置守卫
router.afterEach((to, from) => {
  console.log(to.meta.title); 
  // 通过中央事件总线注册事件传参
  // Vue.prototype.$bus.$emit('getTitle',to.meta.title)
  localStorage.setItem('title',to.meta.title)  
  document.title = to.meta.title
  
})
// 路由导航守卫
router.beforeEach((to,from,next)=>{
  if(to.path=='/login') return next()
  // 获取缓存中的token
  let token = localStorage.getItem('admin_token')
  if (!token) return next('/login') 
  next()
  // to:要访问的路径
  // from:来路
  // next()放行
})
export default router
